<?php

namespace App\Repositories;

use App\Enums\UserEnum;
use App\Enums\FinancialEnum;
use App\Enums\ContentNameEnum;
use App\Enums\CrossRoomPkEnum;
use App\Models\MainDB\Log;
use App\Services\Tools\ContentService;
use App\Services\Tools\FrontHttpRequest;
use App\Traits\AdminLog;
use App\Enums\ActionEnum;
use App\Jobs\QiPao\ExpJob;
use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\CurlService;
use App\Services\Tools\RedisService;
use Illuminate\Support\Facades\Redis;
use App\Services\Tools\HelperService;

//引入hash

class UserRepository
{
    use AdminLog;

    public function addExp($userId, $params)
    {
        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }

        DB::connection("mysql")->transaction(function () use ($userId, $user, $params) {
            $exp = $params['exp'];
            //增加用户经验
            dispatch(new ExpJob($userId, $exp, 2, 0, 1));
        }, 5);

        return true;
    }

    public function resetEmChat($userId, $params)
    {
        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }

        $emChatRes = app("repo_emchat");

        if (env("APP_ENV") != 'production') {
            $emChatRes->deleteUser($user->emchat_username);
            $emChatRes->createUser($user->emchat_username, $user->emchat_password);
        } else {
            $emChatRes->resetPassword($user->emchat_username, $user->emchat_password);
        }

        return true;
    }

    public function setUserRole($userId, $params)
    {
        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }

        DB::connection("mysql")->transaction(function () use ($userId, $user, $params) {
            $type = $params['type'];
            if ($type == 1) {
                app("model_user")->where("user_id", $userId)->update([
                    "role" => 1,
                ]);
            } else {
                app("model_user")->where("user_id", $userId)->update([
                    "role" => 2,
                ]);
            }
        }, 5);
        RedisService::clearUserInfo($userId);

        return true;
    }

    public function setBanUser($userId, $params)
    {
        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }
        $withdrawRecordIds = [];
        DB::connection("mysql")->transaction(function () use ($userId, $user, $params, &$withdrawRecordIds) {
            $action = $params['action'];

            if ($action == 1) {
                //1.2.5家族系统
                if (app('model_family')->where('user_id', $userId)->value('id')){
                    throw new BasicException(100078);
                }

                //计算封禁时间
                $nowTime = time();
                switch ($params['seal_time_type']){
                    case 0:
                        $sealTime = UserEnum::USER_PERPETUAL_TIME;
                        break;
                    case 1:
                        $sealTime = $params['seal_time_int'] * 3600 + $nowTime;
                        break;
                    case 2:
                        $sealTime = $params['seal_time_int'] * 24 * 3600 + $nowTime;
                        break;
                    case 3:
                        $sealTime = $params['seal_time_int'] * 30 * 24 * 3600 + $nowTime;
                        break;
                }
                //$sealTime = is_integer($params['seal_time']) ? $params['seal_time'] : strtotime($params['seal_time']);
                $remark = $params['remark'];
                /*if ($sealTime <= time()) {
                    throw new BasicException(10001, "封禁时间必须大于当前时间！");
                }*/
                //判断是否已经封禁了
                if ($user['seal_time'] >= time()) {
                    throw new BasicException(10001, "该用户已被封禁，请勿重复提交");
                }

                //获取提现列表
                $infoArr = app('model_user_withdraw')->select('gold', 'id', 'bank_type')->where([
                    'user_id' => $userId,
                    'platform_status' => 1,
                    'status' => 1,
                ])->get()->toarray();
                foreach ($infoArr as $key => $value) {

                    if (in_array($value['bank_type'],[FinancialEnum::BANKCARD_WITHDRAW, FinancialEnum::COMPANY_WITHDRAW])) {
                        //将提现状态修改为驳回
                        $updateRes = app('model_user_withdraw')
                            ->where([
                                'id' => $value['id'],
                                'user_id' => $userId,
                                'platform_status' => 1,
                                'status'=>1,
                            ])->update([
                                'platform_status' => 3,
                                'status' => 3,
                                'fail_reason' => "用户被封禁",
                            ]);
                    } else {
                        //将提现状态修改为驳回
                        $updateRes = app('model_user_withdraw')
                            ->where([
                                'id' => $value['id'],
                                'user_id' => $userId,
                                'platform_status' => 1,
                                'status'=>1,
                            ])->update([
                                'platform_status' => 3,
                                'status' => 3,
                                'remark' => "用户被封禁",
                            ]);
                    }
                    if ($updateRes) {
                        $withdrawRecordIds[] = $value['id'];
                        app('repo_account')->change($userId, 24, abs($value['gold']), "已退回", $value['id']);

                        //删除待提现资金日志
                        app('model_account_earnings_log')->where([
                            ["source_id", "=", $value['id']],
                            ["change_type", "=", 23],
                        ])->delete();
                    } else {
                        throw new BasicException(10001, "操作失败！");
                    }
                }
                //需要存操作人姓名
                $adminName = app('model_admin')->where('admin_id', app('request')->admin_id)->value('admin_name') ?? '';
                app("model_user_seal")->create([
                    "user_id"   => $userId,
                    "seal_time" => $sealTime,
                    "remark"    => $remark,
                    "add_time"  => time(),
                    'admin_id'  => app('request')->admin_id,
                    'source' => $params['source'],
                    'url' => $params['url'],
                    'is_ban_auth' => $params['is_ban_auth'],
                    'reason' => $params['reason'],
                    'admin_name' => $adminName
                ]);

                app("model_user")->where("user_id", $userId)->update([
                    "seal_time" => $sealTime,
                ]);

                //封禁身份证号相同的其他用户,v1.2.0 新需求,只封账号,不封实名 2022.11.17 刘沛鑫
                 //获取用户身份证号
                $id_number = app('model_user_auth')->where('user_id',$userId)->whereIn('app_status',[0,1])->pluck('id_number')->toArray();
                $this->otherAccount($id_number,$userId, $params, $sealTime, $adminName);

                Redis::Setex('u:seal:' . $userId, $sealTime - time(), 1);
                if ($sealTime == UserEnum::USER_PERPETUAL_TIME){
                    $sealTimeString = '永久';
                    //永久封禁加入到特殊用户列表
                    app('repo_special_user')->saveSealUser($userId);
                } else {
                    $sealTimeString = date('Y-m-d H:i:s');
                }
                app("repo_admin")->adminLog('封禁' . $user->user_id . $user->user_data->nickname . "到" . $sealTimeString);

                //跨房PK,如果被封禁的用户是主持,并且正在PK中,那么直接发送PK异常的推送
                try {
                    $userRoom = app('model_cross_room_pk')->where('status', CrossRoomPkEnum::CROSS_CONDUCT)
                        ->where(function ($query) use ($userId) {
                            $query->where('pit_user_id', $userId)->orWhere('meet_pit_user_id', $userId);
                        })->latest('id')->first();
                    if ($userRoom){
                        if ($userRoom['pit_user_id'] == $userId){
                            $userRoomId = $userRoom['room_id'];
                        }
                        if ($userRoom['meet_pit_user_id'] == $userId){
                            $userRoomId = $userRoom['meet_room_id'];
                        }
                        if(isset($userRoomId)){
                            app('repo_cross_room_pk')->abnormaHandle($userRoomId, CrossRoomPkEnum::ABNORMAL_HOST);
                        }
                    }
                } catch (\Exception $exception) {
                    \Log::info('PK房出现错误了:'.$exception->getMessage());
                }

            } else {
                app("model_user")->where("user_id", $userId)->update([
                    "seal_time" => 0,
                ]);

                app('repo_special_user')->deleteSealUser($userId);
                //$id_number = app('model_user_auth')->where('user_id',$userId)->whereIn('app_status',[0,1,3])->whereIn('app_status_origin',[0,1,3])->pluck('id_number')->toArray();
                //身份证号相同的，数据解封
                /*$list = app('model_user_auth')->whereIn('id_number', $id_number)->where('is_black', 1)->get();
                foreach ($list as $k => $v) {
                    $v->is_black = 0;
                    $v->reason = $params['reason'] ?? '';
                    $v->app_status = $v['app_status_origin'];
                    $v->update_time = date('Y-m-d H:i:s');
                    $v->save();
                }*/
                //解封记录
                //获取最新一条封禁的时间
                $sealAddTime = app('model_user_seal')->select('add_time')->where('user_id', $userId)->orderBy('id', 'desc')->first()['add_time'] ?? 0;
                app('model_user_untie_log')->create([
                    'user_id'   => $userId,
                    'seal_time' => $sealAddTime,
                    'admin_id'  => app('request')->admin_id,
                    'url' => $params['url'],
                    'reason' => $params['reason'],
                ]);

                Redis::del('u:seal:' . $userId);

                app("repo_admin")->adminLog('解封' . $user->user_id . $user->user_data->nickname);
            }
        }, 5);

        //提现失败的记录通知财务系统
        if (isset($withdrawRecordIds) && $withdrawRecordIds) {
            // 推送到财务系统 financialSys
            $ids = implode(',', $withdrawRecordIds);
            app('repo_user_withdraw')->pushWithdrawDataToFinancialSys($ids);
        }

        return true;
    }

    public function giveGift($userId, $params)
    {
        $number = $params['number'];
        $giftId = $params['gift_id'];
        $remark = $params['remark'] ?? '';
        $adminId = $params['admin_id'];

        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }

        app("repo_gift")->sendBackpackGift($userId, $giftId, $number, $remark, $adminId);

        return true;
    }

    public function userRecharge($userId, $params)
    {
        $money = $params['money'];
        $user = app("model_user")->where("user_id", $userId)->first();
        if (!$user) {
            throw new BasicException(10001, "用户不存在！");
        }
        if ($money > 0 and $user->deleted == 1) {
            throw new BasicException(10001, "用户已注销！");
        }
        if ($money > 0 and $user->disabled != 1) {
            throw new BasicException(10001, "用户已被封禁！");
        }
        DB::beginTransaction();
        try {
            $data = [
                'user_id'     => $userId,
                'user_money'  => $params['money'],
                'change_time' => time(),
                'change_desc' => '平台管理员充值',
                'change_type' => 21,
            ];
            $type = $params['type'];
            $money = $params['money'];

            $update_field = '';
            if ($type == 1) {
                $update_field = 'money';
                $data['change_type'] = $money > 0 ? 21 : 22;
            } elseif ($type == 2) {
                $update_field = 'earnings';
                $data['change_type'] = $money > 0 ? 16 : 17;
                $data['change_desc'] = $money > 0 ? '管理员赠送收益' : '管理员扣除收益';
            }

            if ($money < 0) {
                $abs_money = abs($money);
                if ($user->$update_field < $abs_money) {
                    throw new BasicException(10001, "余额不足！");
                }
            }

            //账户修改并记录日志
            app('repo_account')->change($userId, $data['change_type'], abs($data['user_money']), $data['change_desc'], 0);
            // 资金余额变动同步到大众名单
            app('repo_erm_public_list')->changeSyncToPublicList($userId);

            app("repo_admin_recharge")->addAdminRecharge($userId, $params['admin_id'], $params['type'], $data['user_money'], $params['remark'], $params['purpose']);

        }catch (\Exception $e) {
            DB::rollBack();
            \Log::error('赠送收益失败,error:'.$e->getMessage());
            throw new BasicException(10001, $e->getMessage());
        }
        DB::commit();
        return true;
    }

    /**
     * 平台用户注册总数
     *
     * @param $where
     * @return bool
     */
    public function totalRegisteredUsers($where = [])
    {
        $result = app('model_user')->where($where)->where('deleted', 0)->count();;

        return $result;
    }

    /**
     * 获取用户信息
     *
     * @param $user_id
     * @return array
     */

    public function getUserInfo($user_id)
    {
        $user_info = app('model_user')
            ->where('user_id', $user_id)
            //->where('deleted', 0)
            ->with('user_data')
            ->with(['user_photo'=>function($query){
                $query->where('state','>',-1);
            }])
            ->with('user_score')
            ->first();
        if (!$user_info) {
            return [];
        }
        $rank_id = app('model_user')->upgradeVip($user_id); //调用升级方法
        /*用户经验*/
        //$userExp = round(floatval(app('model_user_exp')->getUserExp($user_id)), 2);
        /*当前等级*/
        $currentGardeRes = app('model_grade_config')->where(['id' => $rank_id])->first();
        if ($currentGardeRes) {
            $currentGarde = ['id' => $currentGardeRes['id'], 'name' => $currentGardeRes['name'], 'head_picture' => $currentGardeRes['head_picture']];
        } else {
            $vip0_icon = env('OBS_HOST') . '/custom/vip0.png';
            $currentGarde = ['id' => 0, 'name' => '0级', 'head_picture' => $vip0_icon];
        }
        $user_info->grade = $currentGarde;
        // 爵位
        $userDetail = RedisService::getUserBaseInfo($user_id);
        //dd($userDetail);
        $user_info->nobility_name = $userDetail['nobility_name'];
        // 是否实名
        $user_info->is_real = empty($user_info->user_data->real_name) ? 0 : 1;
        // 所属工会
        $sociaty = app('model_sc_sociaty_user')
            ->with('sociaty')
            ->where('user_id',$user_id)
            ->first();
        $user_info->sociaty_name = empty($sociaty->sociaty->sociaty_name) ? '无' : $sociaty->sociaty->sociaty_name;
        // 星钻数量
        $gift_number = app('model_gift_backpack')->where('gift_id',538)->where('user_id',$user_id)->first();
        $user_info->sugar_number = empty($gift_number->number) ? 0 : $gift_number->number;
        // 绑定支付宝
        $bank = app('model_user_bank')->where('user_id',$user_id)->where('bank_type',1)->first();
        $user_info->bank_num = empty($bank->bank_num) ? '' : $bank->bank_num;
        // 标签
        $user_label = app('model_user_label')
            ->where('user_id',$user_id)
            ->orderBy('label_id','desc')
            ->with(['label'=>function($query){
                $query->select('id','name');
            }])
            ->first();
        $user_info->label_name = empty($user_label->label->name) ? '' : $user_label->label->name;
        // 设备号
        $device = app('model_user_device')->where('user_id',$user_id)->first();
        $user_info->device_id = empty($device->device_id) ? '' : $device->device_id;
        //获取用户视频审核状态
        $verify = $this->returnUserVerifyStatus($user_id);
        $user_info_vedio = [];
        if ($verify['verify_vedio'] == 1) { //缓存中有待审核的视频
            $user_info_vedio['verify'] = 0;       //0待审核
            $user_info_vedio['vedio'] = $verify['vedio'] ?? '';
            $user_info_vedio['vedio_cover'] = $verify['vedio_cover'] ?? '';
        } else {
            $user = app('model_user_data')->select(['vedio', 'vedio_cover'])->where('user_id', $user_id)->first();
            $user_info_vedio['verify'] = empty($user['vedio']) ? 2 : 1;//2表示没有上传过视频 1通过
            $user_info_vedio['vedio'] = $user['vedio'] ?? '';
            $user_info_vedio['vedio_cover'] = $user['vedio_cover'] ?? '';
        }
        $user_info->vedio = $user_info_vedio;

        return $user_info->toArray();
    }

    public function returnUserVerifyStatus($user_id)
    {
        $verifyInfo = $this->getUserVerifyStatus($user_id);
        $user = [
            ContentNameEnum::NICKNAME     => [
                'key'          => 'verify_nickname',
                'relative_key' => 'nickname',
                'status'       => 2,
                'value'        => '',
            ],
            //2
            ContentNameEnum::HEAD_PICTURE => [
                'key'          => 'verify_head_picture',
                'relative_key' => 'head_picture',
                'status'       => 2,
                'value'        => '',
            ],
            ContentNameEnum::VIDEO_INTRO  => [
                'key'          => 'verify_vedio',
                'relative_key' => 'vedio',
                'status'       => 2,
                'value'        => '',
            ],
            ContentNameEnum::VOICE_INTRO  => [
                'key'          => 'verify_voice',
                'relative_key' => 'intro_voice',
                'status'       => 2,
                'value'        => '',
            ],
            ContentNameEnum::SIGNATURE    => [
                'key'          => 'verify_signature',
                'relative_key' => 'signature',
                'status'       => 2,
                'value'        => '',
            ],
        ];
        foreach ($user as $k => $v) {
            if (isset($verifyInfo[$k]) && $verifyInfo[$k]['status'] == 1) {    //仅获取审核中的记录,对审核拒绝的记录根据封禁状态进行处理,且审核拒绝的记录已经对主表数据进行还原,直接取主表数据没有问题
                $user[$k]['status'] = $verifyInfo[$k]['status'];
                $other_data = empty($verifyInfo[$k]['other_data']) ? [] : $verifyInfo[$k]['other_data'];//审核前数据
                $other_data = is_array($other_data) ? $other_data : json_decode($other_data, true);
                $user[$k]['value'] = [
                    'url'        => !isset($verifyInfo[$k]['url']) ? '' : $verifyInfo[$k]['url'],
                    'other_data' => $other_data,
                ];
            }
        }
        $reUser = [];
        foreach ($user as $k => $v) {
            $reUser[$v['key']] = $v['status'];
            if ($v['status'] == 1) {
                $reUser[$v['relative_key']] = $v['value'];
            }
        }

        if (isset($reUser['nickname'])) {
            $reUser['nickname'] = $reUser['nickname']['url'];
        }
        if (isset($reUser['head_picture'])) {
            $reUser['head_picture'] = $reUser['head_picture']['url'];
        }
        if (isset($reUser['intro_voice'])) {
            $reUser['intro_voice_time'] = isset($reUser['intro_voice']['other_data']['intro_voice_time']) ? $reUser['intro_voice']['other_data']['intro_voice_time'] : 0;
            $reUser['intro_voice'] = $reUser['intro_voice']['url'];
        }
        if (isset($reUser['vedio'])) {
            $reUser['vedio_cover'] = isset($reUser['vedio']['other_data']['vedio_cover']) ? $reUser['vedio']['other_data']['vedio_cover'] : '';
            $reUser['vedio'] = $reUser['vedio']['url'];
        }
        if (isset($reUser['signature'])) {
            $reUser['signature'] = $reUser['signature']['url'];
        }

        return $reUser;
    }

    public function getUserVerifyStatus($user_id, $contentName = '')
    {
        $redisKey = RedisKeyEnum::USER_VERIFY_STATUS . $user_id;
        $redis = app('redis');
        //        $redis = new \Redis();
        if ($contentName) {
            $data = $redis->hget($redisKey, $contentName);
            $data = empty($data) ? [] : json_decode($data, true);
        } else {
            $data = $redis->hGetAll($redisKey);
            foreach ($data as $k => $v) {
                $data[$k] = json_decode($v, true);
            }
        }

        return $data;
    }

    /**
     * 获取当前在线人数
     *
     * @return mixed
     */
    public function getOnlineUserCount()
    {
        $app_online_count = Redis::get('app_online_count');
        if ($app_online_count !== false) {
            $count = $app_online_count;
        } else {
            $count = $this->where('offline_time = 0 and last_online_time > 0')->count();
            Redis::setex('app_online_count', 3600, $count);
        }

        return $count;
    }

    /**
     * 获取需要的用户id
     *
     * @param $where
     * @return bool
     */
    public function getAllUserIds($where = [])
    {
        $user_ids = app('model_user')->where($where)->where('deleted', 0)->pluck('user_id')->toArray();

        return $user_ids;
    }


    /**
     *操作用户收益
     *
     * @param $user_id
     * @param $money
     * @param $type
     * @return bool
     */
    public function serUserEarnings($user_id, $money, $type)
    {
        $where[] = ['user_id', $user_id];
        if ($type == 1) {
            $result = app('model_user')->where($where)->increment('earnings', $money);
        }
        if ($type == 2) {
            $where[] = ['earnings', '>=', $money];
            $result = app('model_user')->where($where)->decrement('earnings', $money);
        }

        return $result;
    }

    /**
     * 操作用户冻结资金
     *
     * @param $user_id
     * @param $money
     * @param $type
     * @return bool
     */
    public function setUserFreezeMoney($user_id, $money, $type)
    {
        if ($type == 1) {
            $result = app('model_user')->where('user_id', $user_id)->increment('freeze_money', $money);
        }
        if ($type == 2) {
            $result = app('model_user')->where('user_id', $user_id)->decrement('freeze_money', $money);
        }

        return $result;
    }

    /**
     * 用户多个金额变动
     *
     * @param $where
     * @param $money
     * @return bool
     */
    public function changeUserMoney($where, $money)
    {
        $result = app('model_user')->where($where)->update(['freeze_money' => DB::raw('freeze_money-' . $money), 'earnings_coin' => DB::raw('earnings_coin+' . $money), 'earnings' => DB::raw('earnings+' . $money)]);

        return $result;
    }


    /**
     * 退款到用户账号
     *
     * @param $money
     * @param $user_id
     * @return bool
     * @throws BasicException
     */

    public function refund($money, $user_id)
    {
        $result = app('model_user')->where('user_id', $user_id)->increment('money', $money);
        if ($result) {
            return $result;
        }
        throw new BasicException(93133);
    }

    public function getNobilityRatio($user_id)
    {
        $ratio = Redis::get('u:nobility:ratio:' . $user_id);
        if ($ratio === false) {
            $ratio = 0;
        }

        return $ratio;
    }

    /**
     * 删除
     */
    public function delUserAccount($idArr = [])
    {
        DB::connection("mysql")->transaction(function () use ($idArr) {
            $res = app('model_user')->whereIn("user_id", $idArr)->delete();
            if (!$res) {
                throw new BasicException(93044);
            }

            $res = app('model_user_data')->whereIn("user_id", $idArr)->delete();
            //            if(!$res) {
            //                throw new BasicException(93044);
            //            }
        }, 5);


        return true;
    }

    /**
     * 修改
     */
    public function saveUserAccount($userId, $params)
    {
        DB::connection("mysql")->transaction(function () use ($userId, $params) {
            $originUser = app("model_user")->where("user_id", $userId)->first();
            if (empty($originUser)) {
                throw new BasicException(10001, "user_id为" . $userId . "的用户并不存在！");
            }

            $originUserData = app("model_user_data")->where("user_id", $userId)->first();
            if (empty($originUserData)) {
                throw new BasicException(10001, "user_id为" . $userId . "的用户数据并不存在！");
            }

            if ($params['gift_bag_id'] != 0) {
                $originGiftBag = app("model_gift_bag")->where("id", $params['gift_bag_id'])->first();
                if (empty($originGiftBag)) {
                    throw new BasicException(10001, "gift_bag_id为" . $params['gift_bag_id'] . "的邀请礼包数据并不存在！");
                }
            }

            if (isset($params['gift_bag_id']) && $params['gift_bag_id'] >= 0) {
                app('model_user')->where("user_id", $userId)->update([
                    "gift_bag_id"       => $params['gift_bag_id'],
                    "gift_bag_quantity" => $params['gift_bag_quantity'],
                ]);
                unset($params['gift_bag_id']);
                unset($params['gift_bag_quantity']);
            }

            // 移除数据
            $params = $this->removeUserData($params,$originUserData);


            if ($originUserData->user_code != $params['user_code']) {
                $check = app("model_user_data")->where('user_code', $params['user_code'])->count();
                if ($check > 0) {
                    throw new BasicException(10001, "该编号已被使用！");
                }

                // 判断之前的号码是否为靓号
                $check = app("model_good_number")->where('good_number', $originUserData->user_code)->count();
                if ($check > 0) {
                    throw new BasicException(10001, "靓号用户无法修改编号,请去靓号页面分配！");
                }
                // 当前传入的号码是否为靓号
                $check = app("model_good_number")->where('good_number', $params['user_code'])->count();

                if ($check > 0) {
                    throw new BasicException(10001, "无法为修改用户保存靓号,请去靓号页面设置！");
                }

                $params['last_user_code'] = $originUserData->user_code;

                // 修改日志
                $affectRows = app('model_user_change')->create([
                    "user_id"     => $userId,
                    "change_from" => $originUserData->user_code,
                    "change_to"   => $params['user_code'],
                    'type'        => 1,
                    'add_time'    => time(),
                ]);
                if (!$affectRows) {
                    throw new BasicException(10001, "修改用户编号日志失败！");
                }
            } else {
                unset($params['user_code']);
            }

            if ($originUserData->nickname != $params['nickname']) {
                $check = app("model_user_data")->where('nickname', $params['nickname'])->count();
                if ($check > 0) {
                    throw new BasicException(10001, "该昵称已被使用！");
                }

                app('redis')->del(sprintf(RedisKeyEnum::USER_INFO, $userId));

                // 修改日志
                $affectRows = app('model_user_change')->create([
                    "user_id"     => $userId,
                    "change_from" => $originUserData->nickname,
                    "change_to"   => $params['nickname'],
                    'type'        => 2,
                    'add_time'    => time(),
                ]);
                if (!$affectRows) {
                    throw new BasicException(10001, "修改昵称日志失败！");
                }
            } else {
                unset($params['nickname']);
            }

            unset($params['id']);
            app('model_user_data')->where('user_id', $userId)->update($params);
        }, 5);

        $params['source_id'] = 0;
        (new FrontHttpRequest())->reportUserInfo($params);

        RedisService::clearUserInfo($userId);

        return true;
    }

    /**
     * 用户移除数据信息
     * @param $params array 请求参数
     * @param $originUser object 用户数据
     * @return mixed
     */
    public function removeUserData($params,$originUser)
    {
        $userNewsData = [
            'user_id' => $originUser->user_id,
            'add_time'=> time()
        ];
        if (!empty($params['head_picture']) && $params['head_picture'] == -1) {
            $params['head_picture'] = HelperService::getRandomHeadPicture();
            $userNewsData['content'] = '您的头像因涉嫌违规已被删除，请重新上传。';
            app('model_user_news')->create($userNewsData);
            unset($params['head_picture_first']);
        }
        if (!empty($params['nickname']) && $params['nickname'] == -1) {
            $userNewsData['content'] = '您的昵称因涉嫌违规已被删除，请重新上传';
            $nickname_prefix = '小冰语';
            $params['nickname'] = $nickname_prefix . $originUser->user_code;
            app('model_user_news')->create($userNewsData);
        }
        if (!empty($params['signature']) && $params['signature'] == -1) {
            $userNewsData['content'] = '您的个性签名因涉嫌违规已被删除，请重新上传';
            app('model_user_news')->create($userNewsData);
            $params['signature'] = '';
        }
        if (!empty($params['intro_voice']) && $params['intro_voice'] == -1) {
            //同时在变更表删除
            $w = [
                'user_id'      => $originUser->user_id,
                'content_name' => ContentNameEnum::VOICE_INTRO,
            ];
            $action = app('model_user_change_action')->where($w)->where('status',1)->first();
            if (!empty($action)) {
                throw new BasicException(0, "语音在审核中，不可删！");
            }
            $userNewsData['content'] = '您的语音签名因涉嫌违规已被删除，请重新上传';
            app('model_user_news')->create($userNewsData);
            $params['intro_voice'] = '';
            $params['intro_voice_time'] = 0;
        }
        if (!empty($params['vedio']) && $params['vedio'] == -1) {
            $w = [
                'user_id'      => $originUser->user_id,
                'content_name' => ContentNameEnum::VIDEO_INTRO,
            ];
            $action = app('model_user_change_action')->where($w)->where('status',1)->first();
            if (!empty($action)) {
                throw new BasicException(0, "视频在审核中，不可删！");
            }
            $userNewsData['content'] = '您的照片墙因涉嫌违规已被删除，请重新上传';
            app('model_user_news')->create($userNewsData);
            $params['vedio'] = '';
            $params['vedio_cover'] = '';
        }
        if (!empty($params['user_photo']) && $params['user_photo'] == -1) {
            $userNewsData['content'] = '您的照片墙因涉嫌违规已被删除，请重新上传';
            app('model_user_news')->create($userNewsData);
            unset($params['user_photo']);
            // 清除表里数据
            app('model_user_photo')->where('user_id',$originUser->user_id)->delete();
        } else if (!empty($params['user_photo'])){
            // 修改照片墙数据
            $originUserPhoto = app('model_user_photo')->where('user_id',$originUser->user_id)->get()->toArray();
            if (!empty($originUserPhoto)) {
                $userPhoto = json_decode($params['user_photo'],true);
                //$userPhoto = $params['user_photo'];
                $userPhotoKey = array_column($userPhoto,'id');
                foreach ($originUserPhoto as $key => $value) {
                    if (in_array($value['id'],$userPhotoKey)) {
                        unset($originUserPhoto[$key]);
                    }
                }
                $delIds = array_column($originUserPhoto,'id');
                app('model_user_photo')->whereIn('id',$delIds)->delete();
            } else {
                $params['user_photo'] = serialize($params['user_photo']);
            }
        }
        // 交友标签
        if (!empty($params['user_label'])) {
            $label_num = app('model_user_label')->where('user_id',$originUser->user_id)->count();
            if ($label_num>0) {
                app('model_user_label')->where('user_id',$originUser->user_id)->update(['label_id'=>$params['user_label']]);
            }else {
                app('model_user_label')->create([
                    'user_id' => $originUser->user_id,
                    'label_id'=>$params['user_label']
                ]);
            }

        }
        unset($params['user_label']);
        unset($params['id']);
        app('redis')->del('user:news:count:'.$originUser->user_id);
        app('redis')->del('user:news:info:'.$originUser->user_id);

        return $params;
    }


    /**
     * 查询用户列表
     */
    public function getUserAccountQueryList(array $params)
    {
        $appType = $params['app_type'] ?? -1;
        $hasGiftBag = $params['has_gift_bag'] ?? -1;
        $sex = $params['sex'] ?? -1; //-1：不限制；0：空；1：男；2：女
        $nickname = $params['nickname'] ?? '';
        $userCode = $params['user_code'] ?? 0;
        $mobile = $params['mobile'] ?? '';
        $registerTimeStart = $params['register_time_start'] ?? '';
        $registerTimeEnd = $params['register_time_end'] ?? '';
        $perPage = $params['perPage'] ?? 10;
        $user_id = $params['user_id'] ?? 0; //用户id
        $status = $params['status'] ?? -1; //状态 0使用中 1封禁 2注销
        $time = time();
        $is_emulator = $params['is_emulator'] ?? -1;
        $where = [];
        if ($appType != -1) {
            $where[] = ['app_type', '=', $appType];
        }
        if ($hasGiftBag == 1) {
            $where[] = ['gift_bag_id', '>', 0];
        } else {
            if ($hasGiftBag == 0) {
                $where[] = ['gift_bag_id', '=', 0];
            }
        }

        if ($status != -1) {
            if ($status == 0){
                $where[] = ['deleted', '=', 0];
                $where[] = ['seal_time', '=', 0];
            } else if ($status == 1){
                $where[] = ['deleted', '=', 1];
            } else if ($status == 2){
                $where[] = ['seal_time', '>=', $time];
                $where[] = ['deleted', '==', 0];
            }
        }
        if ($mobile) {
            $where[] = ['mobile', '=', $mobile];
        }
        if ($registerTimeStart) {
            $where[] = ['register_time', '>=', $registerTimeStart];
        }
        if ($registerTimeEnd) {
            $where[] = ['register_time', '<=', $registerTimeEnd];
        }

        //用户id 条件拼接
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }

        $model = app('model_user')
            ->select(['user_id', 'deleted', 'role', 'user_no', 'mobile', 'gift_bag_id', 'gift_bag_quantity', 'rank_id', 'money', 'coin', 'earnings', 'seal_time', 'register_time', 'app_type', 'earnings_status', 'is_seal_money', 'alipay_acc_num', 'bank_acc_num'])
            ->with([
                'user_data' => function ($query) {
                    $query->select(['user_id', 'head_picture', 'user_code', 'nickname', 'signature', 'birthday', 'constellation', 'profession', 'real_name', 'identity_number', 'sex','is_emulator']);
                },
            ])
            ->with('cancel_account');
        if ($sex != -1) {
            $model = $model->whereHas('user_data', function ($query) use ($sex) {
                $query->where('sex', $sex);
            });
        }

        if ($nickname) {
            $model = $model->whereHas('user_data', function ($query) use ($nickname) {
                $query->where('nickname', 'like', '%' . $nickname . '%');
            });
        }

        if ($userCode) {
            $model = $model->whereHas('user_data', function ($query) use ($userCode) {
                $query->where('user_code', $userCode);
            });
        }
        //新增用户类型搜索
        $sociaty = app('model_sc_sociaty_user');
        if (isset($params['user_type'])){
            if ($params['user_type'] == 0){
                $sociatyUser = $sociaty->select('type', 'user_id')->get()->toArray();
                if (!empty($sociatyUser)){
                    $userIds = array_column($sociatyUser, 'user_id');
                } else {
                    $userIds = [];
                }
                $model = $model->whereNotIn('user_id', $userIds);
            } else {
                $userIds = $sociaty->where('type', $params['user_type'])->pluck('user_id')->toArray();
                $model = $model->whereIn('user_id', $userIds);
            }
        }
        $sociatyUser = $sociaty->select('type', 'user_id')->get()->toArray();
        $userTypes = array_column($sociatyUser, 'type', 'user_id');

        if ($is_emulator != -1){
            $model = $model->whereHas('user_data', function ($query) use ($is_emulator) {
                $query->where('is_emulator', $is_emulator);
            });
        }

        if (!empty($where)) {
            $model = $model->where($where);
        }
        $list = $model
            ->orderByDesc('user_id')
            ->paginate($perPage)->toArray();

        //批量查询用户房间id
        $userIds = array_column($list['data'], 'user_id');
        $roomIdUserIdMap = app('model_user_room')
            ->select('room_id', 'user_id')
            ->whereIn('user_id', $userIds)
            ->pluck('room_id', 'user_id')->toArray();
        //批量用户礼包名称
        $giftBagIds = array_column($list['data'], 'gift_bag_id');
        $giftBagIds = array_unique($giftBagIds);
        $giftBagNameIdMap = app('model_gift_bag')
            ->select('id', 'name as gift_bag_name')
            ->whereIn('id', $giftBagIds)
            ->pluck('gift_bag_name', 'id')->toArray();

        $userChannel = app('model_user_channel')
            ->select('channel_code', 'user_id')
            ->whereIn('user_id', $userIds)
            ->pluck('channel_code', 'user_id')->toArray();

        $userAuth = app('model_user_auth')
            ->select('id_number', 'user_id', 'app_status')
            ->whereIn('user_id', $userIds)
            ->where('app_status', 1)
            ->pluck('id_number', 'user_id')->toArray();

        $temp = [];
        foreach ($list['data'] as $key => $v) {
            $temp[$key]['user_id'] = $v['user_id'] ?? 0;
            $temp[$key]['user_code'] = $v['user_data']['user_code'] ?? 0;
            $temp[$key]['user_no'] = $v['user_no'] ?? '';
            $temp[$key]['role'] = $v['role'] ?? 1;
            $temp[$key]['room_id'] = $roomIdUserIdMap[$v['user_id']] ?? '';
            $temp[$key]['head_picture'] = $v['user_data']['head_picture'] ?? '';
            $temp[$key]['mobile'] = $v['mobile'] ?? '';
            $temp[$key]['nickname'] = $v['user_data']['nickname'] ?? '';
            $temp[$key]['gift_bag_name'] = $giftBagNameIdMap[$v['gift_bag_id']] ?? '';
            $temp[$key]['gift_bag_quantity'] = $v['gift_bag_quantity'] ?? '';
            $temp[$key]['gift_bag_id'] = $v['gift_bag_id'] ?? '';
            $temp[$key]['rank_id'] = $v['rank_id'] ?? '';
            $temp[$key]['money'] = $v['money'] ?? 0;
            $temp[$key]['coin'] = $v['coin'] ?? 0;
            $temp[$key]['earnings'] = $v['earnings'] ?? 0;
            $temp[$key]['seal_time'] = $v['seal_time'] > 0 ? date("Y-m-d H:i:s", $v['seal_time']) : '';
            $temp[$key]['register_time'] = $v['register_time'] > 0 ? date("Y-m-d H:i:s", $v['register_time']) : '';
            $temp[$key]['sex'] = $v['user_data']['sex'] ?? 0;
            $temp[$key]['signature'] = $v['user_data']['signature'] ?? '';
            $temp[$key]['birthday'] = $v['user_data']['birthday'] ?? '';
            $temp[$key]['constellation'] = $v['user_data']['constellation'] ?? '';
            $temp[$key]['profession'] = $v['user_data']['profession'] ?? '';
            $temp[$key]['real_name'] = $v['user_data']['real_name'] ?? '';
            $temp[$key]['identity_number'] = $userAuth[$v['user_id']] ?? '';
            $temp[$key]['exp'] = $v['exp'] ?? 0;
            $temp[$key]['earnings_status'] = $v['earnings_status'] ?? 1;
            $temp[$key]['is_seal_money'] = $v['is_seal_money'] ?? 1;
            $temp[$key]['is_cancel'] = $v['deleted'] ?? 0;
            $temp[$key]['alipay_acc_num'] = $v['alipay_acc_num'] ?? 1;
            $temp[$key]['bank_acc_num'] = $v['bank_acc_num'] ?? 1;
            $temp[$key]['user_type'] = !isset($userTypes[$v['user_id']]) ? 0 : $userTypes[$v['user_id']];
            $temp[$key]['channel_no'] = $userChannel[$v['user_id']] ?? '';
            //用户状态
            if ($v['deleted'] == 1){
                $temp[$key]['status'] = 1;
            } elseif ($v['seal_time'] >= $time){
                $temp[$key]['status'] = 2;
            } else {
                $temp[$key]['status'] = 0;
            }
            $temp[$key]['is_emulator'] = $v['user_data']['is_emulator'] == 1 ? '模拟器' : '其他';
        }
        $list['data'] = $temp;

        return $list;
    }

    /**
     * 新增
     *
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addUserGiftBag($params)
    {
        DB::connection("mysql")->transaction(function () use ($params) {
            $userGiftData = [
                "name"     => $params['name'],
                "status"   => $params['status'],
                "add_time" => time(),
            ];
            $newGiftBag = app('model_gift_bag')->create($userGiftData);

            // 处理礼包详情
            $detailStr = $params['gift_bag_detail'];
            $detailList = json_decode($detailStr, 1);

            if (json_last_error() || !is_array($detailList)) {
                throw new BasicException(10001, "json格式不合法!");
            }

            $insertArr = [];
            foreach ($detailList as $giftBagDetail) {
                if (!isset($giftBagDetail['type']) || !in_array($giftBagDetail['type'], [1, 2, 3, 4])) {
                    throw new BasicException(10001, "type不合法!");
                }

                $temp = [
                    'gift_bag_id'  => $newGiftBag->id,
                    'type'         => $giftBagDetail['type'],
                    'add_time'     => time(),
                    'gold'         => 0,
                    'foreign_id'   => 0,
                    'quantity'     => 0,
                    'name'         => "",
                    'days'         => 0,
                    "expired_time" => 0,
                ];

                switch ($giftBagDetail['type']) {
                    case 1:
                        if (empty($giftBagDetail['gold'])) {
                            throw new BasicException(10001, "添加金币时gold不能为0!");
                        }
                        if (!is_int($giftBagDetail['gold'])) {
                            throw new BasicException(10001, "金币必须为整数!");
                        }

                        $temp['name'] = "金币";
                        $temp['gold'] = $giftBagDetail['gold'];
                        break;
                    case 2:
                        $giftRes = app("model_gift")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["type", '=', 3],
                            ["sold", '=', 1],
                        ])->first();

                        if (empty($giftRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的礼物id!");
                        }
                        if (empty($giftBagDetail['quantity']) || $giftBagDetail['quantity'] < 0) {
                            throw new BasicException(10001, "添加礼物时数量不能为0!");
                        }
                        if (!is_int($giftBagDetail['quantity'])) {
                            throw new BasicException(10001, "礼物必须为整数!");
                        }

                        $temp['foreign_id'] = $giftRes->id;
                        $temp['name'] = $giftRes->name;
                        $temp['quantity'] = $giftBagDetail['quantity'];
                        break;
                    case 3:
                        $rideRes = app("model_mall_products")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["category_id", '=', 2],
                        ])->first();

                        if (empty($rideRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的坐骑id!");
                        }
                        if (empty($giftBagDetail['days']) || $giftBagDetail['days'] < 0) {
                            throw new BasicException(10001, "添加坐骑时天数不能为0!");
                        }
                        if (!is_int($giftBagDetail['days'])) {
                            throw new BasicException(10001, "坐骑天数必须为整数!");
                        }

                        $temp['foreign_id'] = $rideRes->id;
                        $temp['name'] = $rideRes->title;
                        $temp['expired_time'] = time() + 86400 * $giftBagDetail['days'];
                        $temp['days'] = $giftBagDetail['days'];
                        break;
                    case 4:
                        $headRes = app("model_mall_products")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["category_id", '=', 1],
                        ])->first();

                        if (empty($headRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的挂件id!");
                        }
                        if (empty($giftBagDetail['days']) || $giftBagDetail['days'] < 0) {
                            throw new BasicException(10001, "添加挂件时天数不能为0!");
                        }
                        if (!is_int($giftBagDetail['days'])) {
                            throw new BasicException(10001, "挂件天数必须为整数!");
                        }

                        $temp['foreign_id'] = $headRes->id;
                        $temp['name'] = $headRes->title;
                        $temp['expired_time'] = time() + 86400 * $giftBagDetail['days'];
                        $temp['days'] = $giftBagDetail['days'];
                        break;
                }
                $insertArr[] = $temp;
            }

            DB::connection("mysql")->table(app('model_gift_bag_detail')->getTable())->insert($insertArr);
        }, 5);

        return true;
    }

    /**
     * 删除
     */
    public function delUserGiftBag($idArr = [])
    {
        DB::connection("mysql")->transaction(function () use ($idArr) {
            $res = app('model_gift_bag')->whereIn("id", $idArr)->delete();
            if (!$res) {
                throw new BasicException(93044);
            }

            $res = app('model_gift_bag_detail')->whereIn("gift_bag_id", $idArr)->delete();
            if ($res === false) {
                throw new BasicException(93044);
            }

            $res = app('model_user')->whereIn("gift_bag_id", $idArr)->update([
                'gift_bag_id'       => 0,
                'gift_bag_quantity' => 0,
            ]);
            if ($res === false) {
                throw new BasicException(93044);
            }
        }, 5);


        return true;
    }

    /**
     * 修改
     */
    public function saveUserGiftBag($id, $params)
    {
        DB::connection("mysql")->transaction(function () use ($id, $params) {
            $giftBagRes = app('model_gift_bag')->where("id", $id)->first();
            if (empty($giftBagRes)) {
                throw new BasicException(10001, "礼包不存在!");
            }

            app('model_gift_bag')->where("id", $id)->update([
                "name"   => $params['name'],
                "status" => $params['status'],
            ]);

            // 处理礼包详情
            $detailStr = $params['gift_bag_detail'];
            $detailList = json_decode($detailStr, 1);

            if (json_last_error() || !is_array($detailList)) {
                throw new BasicException(10001, "json格式不合法!");
            }

            $insertArr = [];
            foreach ($detailList as $giftBagDetail) {
                if (!isset($giftBagDetail['type']) || !in_array($giftBagDetail['type'], [1, 2, 3, 4])) {
                    throw new BasicException(10001, "type不合法!");
                }

                $temp = [
                    'gift_bag_id'  => $giftBagRes->id,
                    'type'         => $giftBagDetail['type'],
                    'add_time'     => time(),
                    'gold'         => 0,
                    'foreign_id'   => 0,
                    'quantity'     => 0,
                    'name'         => "",
                    'days'         => 0,
                    "expired_time" => 0,
                ];

                switch ($giftBagDetail['type']) {
                    case 1:
                        if (empty($giftBagDetail['gold'])) {
                            throw new BasicException(10001, "添加金币时gold不能为0!");
                        }
                        if (!is_int($giftBagDetail['gold'])) {
                            throw new BasicException(10001, "金币必须为整数!");
                        }

                        $temp['name'] = "金币";
                        $temp['gold'] = $giftBagDetail['gold'];
                        break;
                    case 2:
                        $giftRes = app("model_gift")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["type", '=', 3],
                            ["sold", '=', 1],
                        ])->first();

                        if (empty($giftRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的礼物id!");
                        }
                        if (empty($giftBagDetail['quantity']) || $giftBagDetail['quantity'] < 0) {
                            throw new BasicException(10001, "添加礼物时数量不能为0!");
                        }
                        if (!is_int($giftBagDetail['quantity'])) {
                            throw new BasicException(10001, "礼物必须为整数!");
                        }

                        $temp['foreign_id'] = $giftRes->id;
                        $temp['name'] = $giftRes->name;
                        $temp['quantity'] = $giftBagDetail['quantity'];
                        break;
                    case 3:
                        $rideRes = app("model_mall_products")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["category_id", '=', 2],
                        ])->first();

                        if (empty($rideRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的坐骑id!");
                        }
                        if (empty($giftBagDetail['days']) || $giftBagDetail['days'] < 0) {
                            throw new BasicException(10001, "添加坐骑时天数不能为0!");
                        }
                        if (!is_int($giftBagDetail['days'])) {
                            throw new BasicException(10001, "坐骑天数必须为整数!");
                        }

                        $temp['foreign_id'] = $rideRes->id;
                        $temp['name'] = $rideRes->title;
                        $temp['expired_time'] = time() + 86400 * $giftBagDetail['days'];
                        $temp['days'] = $giftBagDetail['days'];
                        break;
                    case 4:
                        $headRes = app("model_mall_products")->where([
                            ["id", '=', $giftBagDetail['foreign_id']],
                            ["category_id", '=', 1],
                        ])->first();

                        if (empty($headRes)) {
                            throw new BasicException(10001, $giftBagDetail['foreign_id'] . "不是合法的挂件id!");
                        }
                        if (empty($giftBagDetail['days']) || $giftBagDetail['days'] < 0) {
                            throw new BasicException(10001, "添加挂件时天数不能为0!");
                        }
                        if (!is_int($giftBagDetail['days'])) {
                            throw new BasicException(10001, "挂件天数必须为整数!");
                        }

                        $temp['foreign_id'] = $headRes->id;
                        $temp['name'] = $headRes->title;
                        $temp['expired_time'] = time() + 86400 * $giftBagDetail['days'];
                        $temp['days'] = $giftBagDetail['days'];
                        break;
                }
                $insertArr[] = $temp;
            }

            $res = app('model_gift_bag_detail')->where("gift_bag_id", $giftBagRes->id)->delete();
            if (!$res) {
                throw new BasicException(93044);
            }

            DB::connection("mysql")->table(app('model_gift_bag_detail')->getTable())->insert($insertArr);
        }, 5);

        return true;
    }

    /**
     * 下拉框内容
     */
    public function getUserGiftBagSelectList()
    {
        $giftRes = app("model_gift")->where([
            ["type", '=', 3],
            ["sold", '=', 1],
        ])->get();

        $rideRes = app("model_mall_products")->with('one_mall_products_price:product_id,day')->where([
            ["category_id", '=', 2],
        ])->get();
        foreach ($rideRes as $item) {
            $item->day = $item->one_mall_products_price->day ?? 0;
            unset($item->one_mall_products_price);
        }

        $headRes = app("model_mall_products")->with('one_mall_products_price:product_id,day')->where([
            ["category_id", '=', 1],
        ])->get();
        foreach ($headRes as $item) {
            $item->day = $item->one_mall_products_price->day ?? 0;
            unset($item->one_mall_products_price);
        }

        //新增6种商品类型
        $tagList = [
            'nctx' => '昵称特效',
            'ncgj' => '昵称挂件',
            'qfgb' => '全服广播',
            'ltqp' => '聊天气泡',
            'sb'   => '声波',
            'gpqp' => '公屏气泡',
        ];

        $result = [
            'ride' => $rideRes,
            'head' => $headRes,
            'gift' => $giftRes,
        ];

        foreach ($tagList as $k => $tag) {
            $result[$k] = [];
            $cateId = app('model_mall_categories')->where(['title' => $tag])->value('id');
            if (!$cateId) {
                continue;
            }
            $tmp = app("model_mall_products")->with('one_mall_products_price:product_id,day')->where([
                ["category_id", '=', $cateId],
            ])->get()->toArray();
            if (!$tmp) {
                continue;
            }
            foreach ($tmp as &$item) {
                $str = json_decode($item['special'], true);
                if (json_last_error() == JSON_ERROR_NONE) {
                    $item['special'] = $str;
                }
                $item['day'] = $item['one_mall_products_price']['day'] ?? 0;
                unset($item['one_mall_products_price']);
            }
            $result[$k] = $tmp;
        }

        return $result;
    }

    //操作用户可用余额
    public function serUserMoney($userId, $money, $type)
    {
        if ($type == 1) {
            $result = app("model_user")->where("user_id", $userId)->increment('money', $money);
        } elseif ($type == 2) {
            $result = app("model_user")->where([
                ["user_id", "=", $userId],
                ["money", ">=", $money],
            ])->decrement('money', $money);
        }

        return $result;
    }

    /**
     * 赠送
     */
    public function sendUserGiftBag($id, $userIdArr, $adminId)
    {
        $giftBagRes = app('model_gift_bag')->where("id", $id)->first();
        if (empty($giftBagRes)) {
            throw new BasicException(10001, "礼包不存在!");
        }

        $giftBagDetailRes = app('model_gift_bag_detail')->where("gift_bag_id", $id)->get();
        if (count($giftBagDetailRes) <= 0) {
            throw new BasicException(10001, "礼包空空的!");
        }
        DB::connection("mysql")->transaction(function () use ($userIdArr, $giftBagDetailRes, $giftBagRes, $adminId) {
            foreach ($userIdArr as $userId) {
                app('model_gift_bag_receive')->create([
                    'user_id'     => $userId,
                    'parent_id'   => 0,
                    'gift_bag_id' => $giftBagRes->id,
                    'add_time'    => time(),
                ]);
                $gd = [];
                foreach ($giftBagDetailRes as $detail) {
                    switch ($detail->type) {
                        case 1: //赠送金币
                            $gd[] = '金币 X ' . $detail->gold;
                            $this->serUserMoney($userId, $detail->gold, 1);
                            //账户修改并记录日志
                            app('repo_account')->change($userId, 34, $detail->gold, $giftBagRes->name, 0);

                            break;
                        case 2: //赠送礼物到背包
                            $gd[] = $detail->name . ' X ' . $detail->quantity . '个';
                            app("repo_gift")->sendBackpackGift($userId, $detail->foreign_id, $detail->quantity, '', $adminId);
                            break;
                        case 3: //赠送坐骑
                        case 4: //赠送头像框
                            $gd[] = $detail->name . ' X ' . $detail->days . '天';
                            app("repo_mall_orders")->give($detail->foreign_id, $userId, $detail->days);
                            break;
                    }
                }
                $title = $giftBagRes['name'];
                $content = '尊敬的用户：恭喜您获得' . $title . '。礼包内容：' . implode('、', $gd);

                $userNewsData = [
                    'user_id'  => $userId,
                    'content'  => $content,
                    'add_time' => time(),
                    'status'   => 0,
                    'title'    => $title,
                ];
                app("repo_user_news")->userNewsAdd($userNewsData);
            }
        }, 5);

        return true;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserGiftBagQueryList(array $params)
    {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_gift_bag')
            ->with("gift_bag_detail")
            ->where($whereArr)->where($whereFunc)->orderBy('id', 'desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = empty($item->add_time) ? '' : date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserBanQueryList(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }
        if (!empty($params["admin_id"])) { //管理员id
            $whereArr[] = ["t1.admin_id", "=", $params["admin_id"]];
        }
        if (!empty($params["mobile"])) {
            $whereArr[] = ["t3.mobile", "=", $params["mobile"]];
        }
        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", '%' . $params["nickname"] . '%'];
        }
        if (!empty($params["remark"])) {
            $whereArr[] = ["t1.remark", "like", '%' . $params['remark'] . '%'];
        }
        if (!empty($params["start_time"]) && !empty($params["end_time"])) {
            $whereArr[] = ["t1.add_time", ">=", $params["start_time"]];
            $whereArr[] = ["t1.add_time", "<", $params["end_time"]];
        }
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userSealModel = app('model_user_seal');
        $userModel = app('model_user');
        $userDataModel = app('model_user_data');
        $adminInfo = app('model_admin');


        $result = app('model_user_seal')
            ->from($userSealModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.mobile",
            ])->selectRaw("t4.admin_name as new_admin_name")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($adminInfo->getTable() . " as t4"), "t1.admin_id", "=", "t4.admin_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->seal_time = empty($item->seal_time) ? '' : date("Y-m-d H:i:s", $item->seal_time);
            $item->add_time = empty($item->add_time) ? '' : date("Y-m-d H:i:s", $item->add_time);
            $item->mobile = strReplaces($item->mobile, 3,4,'*');
            //封禁时长计算
            if ($item->seal_time >= date("Y-m-d H:i:s", UserEnum::USER_PERPETUAL_TIME)){
                $item->seal_time_string = '永久';
            } else {
                $item->seal_time_string = $this->timeCalculation($item->add_time, $item->seal_time);
            }
            //如果不为空,说明该操作员没有被删除
            if (!empty($item->new_admin_name)){
                $item->admin_name = $item->new_admin_name;
            }
        }

        return $result;
    }

    /**
     * @Desc:时间转化字符串
     * @param $beginDate
     * @param $endDate
     * @return string
     * @author: shiquan
     * @Time: 2022/11/4 11:47
     */
    function timeCalculation($beginDate, $endDate)
    {
        $subTime = strtotime($endDate) - strtotime($beginDate);
        $month = $subTime >= 86400*30 ? floor($subTime / 86400/30) : 0;
        $subTime -=$month*30*86400;

        $day = $subTime >= 86400 ? floor($subTime / 86400) : 0;
        $subTime -= $day * 86400;

        $hour = $subTime >= 3600 ? floor($subTime / 3600) : 0;

        $monthText = $month ? $month.'月' : '';
        $dayText = $day ? $day . '天' : '';
        $hourText = $hour ? $hour . '小时' : '';

        $dateH = $monthText . $dayText . $hourText;

        return $dateH;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserUntieQueryList(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["mobile"])) {
            $whereArr[] = ["t3.mobile", "=", $params["mobile"]];
        }
        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", '%' . $params["nickname"] . '%'];
        }

        if (!empty($params["start_time"]) && !empty($params["end_time"])) {
            $params['start_time'] = date('Y-m-d H:i:s', $params['start_time']);
            $params['end_time'] = date('Y-m-d H:i:s', $params['end_time']);
            $whereArr[] = ["t1.created_at", ">=", $params["start_time"]];
            $whereArr[] = ["t1.created_at", "<", $params["end_time"]];
        }
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];

        $userSealModel = app('model_user_untie_log');
        $userModel = app('model_user');
        $userDataModel = app('model_user_data');
        $adminInfo = app('model_admin');

        $result = app('model_user_untie_log')
            ->from($userSealModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.mobile",
                "t4.admin_name",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($adminInfo->getTable() . " as t4"), "t1.admin_id", "=", "t4.admin_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($pageSize, ['*'], '', $page);

        foreach ($result as $item) {
            $item->seal_time = empty($item->seal_time) ? '' : date("Y-m-d H:i:s", $item->seal_time);
            $item->mobile = strReplaces($item->mobile, 3,4,'*');
        }

        return $result;
    }

    /** 获取所有的封禁纪录
     *
     * @param  array  $params
     * @return mixed
     */
    public function getUserBanQueryAll(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }
        if (!empty($params["admin_id"])) { //管理员id
            $whereArr[] = ["t1.admin_id", "=", $params["admin_id"]];
        }
        if (!empty($params["mobile"])) {
            $whereArr[] = ["t3.mobile", "=", $params["mobile"]];
        }
        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", '%' . $params["nickname"] . '%'];
        }
        if (!empty($params["remark"])) {
            $whereArr[] = ["t1.remark", "like", '%' . $params['remark'] . '%'];
        }
        if (!empty($params["start_time"]) && !empty($params["end_time"])) {
            $whereArr[] = ["t1.add_time", ">=", $params["start_time"]];
            $whereArr[] = ["t1.add_time", "<", $params["end_time"]];
        }
        $whereFunc = function ($query) use ($params) {
        };


        $userSealModel = app('model_user_seal');
        $userModel = app('model_user');
        $userDataModel = app('model_user_data');
        $adminInfo = app('model_admin');


        $result = app('model_user_seal')
            ->from($userSealModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.mobile",
            ])->selectRaw("t4.admin_name as new_admin_name")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($adminInfo->getTable() . " as t4"), "t1.admin_id", "=", "t4.admin_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->get();

        foreach ($result as $item) {
            $item->seal_time = empty($item->seal_time) ? '' : date("Y-m-d H:i:s", $item->seal_time);
            $item->add_time = empty($item->add_time) ? '' : date("Y-m-d H:i:s", $item->add_time);
            //封禁时长计算
            if ($item->seal_time >= date("Y-m-d H:i:s", UserEnum::USER_PERPETUAL_TIME)){
                $item->seal_time_string = '永久';
            } else {
                $item->seal_time_string = $this->timeCalculation($item->add_time, $item->seal_time);
            }
            if ($item->is_ban_auth == 1){
                $item->is_ban_auth = '是';
            } else {
                $item->is_ban_auth = '否';
            }
            //如果不为空,说明该操作员没有被删除
            if (!empty($item->new_admin_name)){
                $item->admin_name = $item->new_admin_name;
            }
            $item->nickname = HelperService::wxNickNameFormat($item->nickname);
        }

        return $result;
    }

    /**
     * @Desc:封禁记录导出
     * @param  array  $params
     * @return mixed
     * @author: shiquan
     * @Time: 2022/11/8 17:27
     */
    public function getUserUntieQueryAll(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["mobile"])) {
            $whereArr[] = ["t3.mobile", "=", $params["mobile"]];
        }
        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", '%' . $params["nickname"] . '%'];
        }

        if (!empty($params["start_time"]) && !empty($params["end_time"])) {
            $params['start_time'] = date('Y-m-d H:i:s', $params['start_time']);
            $params['end_time'] = date('Y-m-d H:i:s', $params['end_time']);
            $whereArr[] = ["t1.created_at", ">=", $params["start_time"]];
            $whereArr[] = ["t1.created_at", "<", $params["end_time"]];
        }
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];

        $userSealModel = app('model_user_untie_log');
        $userModel = app('model_user');
        $userDataModel = app('model_user_data');
        $adminInfo = app('model_admin');

        $result = app('model_user_untie_log')
            ->from($userSealModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.mobile",
                "t4.admin_name",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($adminInfo->getTable() . " as t4"), "t1.admin_id", "=", "t4.admin_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($pageSize, ['*'], '', $page);
        foreach ($result as $item) {
            $item->seal_time = empty($item->seal_time) ? '' : date("Y-m-d H:i:s", $item->seal_time);
            $item->nickname = HelperService::wxNickNameFormat($item->nickname);
        }

        return $result;
    }

    /**
     * 删除
     */
    public function delUserBan($idArr = [])
    {
        $res = app('model_user_seal')->whereIn("id", $idArr)->delete();

        if ($res) {
            return $res;
        }
        throw new BasicException(93044);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserChangeQueryList(array $params)
    {
        $whereArr = [];
        $nickname = isset($params["nickname"]) ? $params["nickname"] : ''; //修改前后昵称
        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["user_id"])) {
            $whereArr[] = ["t1.user_id", "=", $params["user_id"]];
        }

        if (!empty($params["type"])) {
            $whereArr[] = ["t1.type", "=", $params["type"]];
        }
        //时间段查询 左闭右开区间
        if (!empty($params["start_time"]) && !empty($params["end_time"])) {
            $whereArr[] = ["t1.add_time", ">=", $params["start_time"]];
            $whereArr[] = ["t1.add_time", "<", $params["end_time"]];
        }

        if (!empty($params["user_id"])) { //用户id
            $whereArr[] = ["t1.user_id", "=", $params["user_id"]];
        }

        //        if (!empty($params["nickname"])) {
        //            $whereArr[] = ["t2.nickname", "like", "%". $params["nickname"] . "%"];
        //        }

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userChangeModel = app('model_user_change');
        $userDataModel = app('model_user_data');


        $result = app('model_user_seal')
            ->from($userChangeModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->where(function ($query) use ($nickname) {
                if (!empty($nickname)) {
                    $query->where('t1.change_from', 'like', '%' . $nickname . '%')
                        ->orWhere('t1.change_to', 'like', '%' . $nickname . '%');
                }
            })
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = empty($item->add_time) ? '' : date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    //冻结背包礼物
    public function freezeBackpackGift($id, $params)
    {
        DB::connection("mysql")->transaction(function () use ($id, $params) {
            $state = $params['state'];

            $item = app('model_gift_backpack')->where("id", $id)->first();

            $item->state = $state;

            $item->save();
        }, 5);

        return true;
    }

    /** 批量冻结背包礼物
     *
     * @param  array  $idArr  gift_backpack的id组成的一维数组
     * @return bool
     * @throws \Throwable
     */
    public function vastFreezeBackpackGift(array $idArr)
    {
        DB::connection("mysql")->transaction(function () use ($idArr) {
            $model = app('model_gift_backpack')->whereIn('id', $idArr)->where('state', 1);
            $item = $model->get()->toArray();
            if (empty($item)) {
                throw new BasicException(10001, '请输入最少一个有效的id值');
            }

            $model->update(['state' => 2]);
        }, 5);

        return true;
    }

    //删除背包礼物
    public function delBackpackGift($idArr)
    {
        DB::connection("mysql")->transaction(function () use ($idArr) {
            $list = app('model_gift_backpack')->whereIn("id", $idArr)->get();
            app('model_gift_backpack')->whereIn("id", $idArr)->delete();
        }, 5);

        return true;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserBackpackQueryList(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["gift_id"])) {
            $whereArr[] = ["t1.gift_id", "=", $params["gift_id"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }
        $whereArr[] = ['t1.number', '>', 0];
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $giftBackpackModel = app('model_gift_backpack');
        $userDataModel = app('model_user_data');
        $giftModel = app('model_gift');

        $result = app('model_gift_backpack')
            ->from($giftBackpackModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.name",
                "t3.price",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($giftModel->getTable() . " as t3"), "t1.gift_id", "=", "t3.id")
            ->where($whereArr)->where($whereFunc);

        if (!empty($params["price_order"])) {
            $sortWay = $params["price_order"] == 1 ? 'asc' : "dasc"; //1升序 2降序
            $result = $result->orderBy('t3.price', $sortWay);
        } else {
            $result = $result->orderBy('t1.id', 'desc');
        }


        $result = $result->paginate($perPage, ['*'], '', $page);


        return $result;
    }

    // todo 获取所有用户背包礼物
    public function getAllUserBackpackGift(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["gift_id"])) {
            $whereArr[] = ["t1.gift_id", "=", $params["gift_id"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }

        $giftBackpackModel = app('model_gift_backpack');
        $userDataModel = app('model_user_data');
        $giftModel = app('model_gift');

        $result = app('model_gift_backpack')
            ->from($giftBackpackModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t3.name",
                "t3.price",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($giftModel->getTable() . " as t3"), "t1.gift_id", "=", "t3.id")
            ->where($whereArr)->orderBy('t1.id', 'desc')->get()->toArray();


        return $result;
    }

    // ip封禁设置
    public function ipBanSet($id, $params)
    {
        DB::connection("mysql")->transaction(function () use ($id, $params) {
            $device_info = app("model_user_device")->where("id", $id)->first();
            if (!$device_info) {
                throw new BasicException(10001, "数据有误");
            }

            $state = $params['ip_state'];

            if ($state == 0) {
                $remark = $params['remark'];
                app("model_user_device")->where('ip', $device_info['ip'])->update([
                    'ip_state'       => 0,
                    'ip_remark'      => $remark,
                    'ip_seal_time'   => time(),
                    "ip_unseal_time" => 0,
                ]);

                Redis::sadd('seal:ip', $device_info['ip']);
            } else {
                app("model_user_device")->where('ip', $device_info['ip'])->update([
                    'ip_state'       => 1,
                    'ip_unseal_time' => time(),
                    'ip_remark'      => "",
                    'ip_seal_time'   => 0,
                ]);

                Redis::srem('seal:ip', $device_info['ip']);
            }
        }, 5);

        return true;
    }

    // 设备封禁设置
    public function deviceBanSet($id, $params)
    {
        DB::connection("mysql")->transaction(function () use ($id, $params) {
            $device_info = app("model_user_device")->where("id", $id)->first();
            if (!$device_info) {
                throw new BasicException(10001, "数据有误");
            }

            $state = $params['state'];
            if ($state == 0) {
                $remark = $params['remark'];

                app("model_user_device")->where('device_id', $device_info['device_id'])->update([
                    'state'       => 0,
                    'seal_time'   => time(),
                    'seal_remark' => $remark,
                    'unseal_time' => 0,
                ]);

                Redis::sadd('seal:device', $device_info['device_id']);
            } else {
                app("model_user_device")->where('device_id', $device_info['device_id'])->update([
                    'state'       => 1,
                    'unseal_time' => time(),
                    'seal_time'   => 0,
                    'seal_remark' => "",
                ]);

                Redis::srem('seal:device', $device_info['device_id']);
            }
        }, 5);

        return true;
    }

    //查询用户设备列表
    public function getDeviceQueryList(array $params)
    {
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userDeviceWhere = $userDataWhere = [];
        //user_device表筛选条件
        if (!empty($params["device_id"])) {
            $userDeviceWhere[] = ["device_id", "=", $params["device_id"]];
        }
        if (!empty($params["ip"])) {
            $userDeviceWhere[] = ["ip", "=", $params["ip"]];
        }

        //user_data表筛选条件
        if (!empty($params["sex"])) {
            $userDataWhere[] = ["sex", "=", $params["sex"]];
        }
        if (!empty($params["user_code"])) {
            $userDataWhere[] = ["user_code", "=", $params["user_code"]];
        }
        if (!empty($params["nickname"])) {
            $userDataWhere[] = ["nickname", "like", "%" . $params["nickname"] . "%"];
        }

        if (!empty($params["is_emulator"])) {
            $userDeviceWhere[] = ["is_emulator", "=", $params["is_emulator"]];
        }
        if (!empty($params['device_name'])){
            $userDataWhere[] = ["device_name", "=", $params["device_name"]];
        }

        $list = app('model_user_device')
            ->select('id', 'user_id', 'client_type', 'device_id', 'device_name', 'ip', 'add_time', 'state', 'ip_state', 'seal_remark', 'ip_remark', 'is_emulator')
            ->where($userDeviceWhere)
            ->with([
                'user_data' => function ($query) use ($userDataWhere) {
                    $query->select('user_id', 'user_code', 'nickname', 'sex', 'head_picture');
                },
            ]);
        if ($userDataWhere) {
            $list = $list->whereHas('user_data', function ($query) use ($userDataWhere) {
                $query->where($userDataWhere);
            });
        }
        $list = $list->orderByDesc('id')->paginate($perPage);

        foreach ($list as &$v) {
            $v->add_time = date("Y-m-d H:i:s", $v->add_time);
            if ($v->user_data) {
                foreach ($v->user_data->toArray() as $k => $v2) {
                    $v->$k = $v2;
                }
            }
            unset($v->user_data);
        }

        return $list;
    }

    /*
     * 获取所有用户的设备信息
     */
    public function getAllUserDriver(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["sex"])) {
            $whereArr[] = ["t2.sex", "=", $params["sex"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }

        if (!empty($params["ip"])) {
            $whereArr[] = ["t1.ip", "=", $params["ip"]];
        }
        if (!empty($params["device_id"])) {
            $whereArr[] = ["t1.device_id", "=", $params["device_id"]];
        }
        if (!empty($params["is_emulator"])) {
            $whereArr[] = ["t1.is_emulator", "=", $params["is_emulator"]];
        }

        $whereFunc = function ($query) use ($params) {
        };

        $giftBackpackModel = app('model_user_device');
        $userDataModel = app('model_user_data');

        $result = app('model_gift_backpack')
            ->from($giftBackpackModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t2.sex",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->get();
        foreach ($result as $item) {
            $item->state = $item->state == 0 ? '封禁' : '正常';
            $item->ip_state = $item->ip_state == 0 ? '封禁' : '正常';
            $item->sex = $item->sex == 1 ? '男' : '女';
            $item->add_time = date("Y-m-d H:i:s", $item->add_time);
            $item->ip_seal_time = empty($item->ip_seal_time) ? "" : date("Y-m-d H:i:s", $item->ip_seal_time);
            $item->ip_unseal_time = empty($item->ip_unseal_time) ? "" : date("Y-m-d H:i:s", $item->ip_unseal_time);
            $item->seal_time = empty($item->seal_time) ? "" : date("Y-m-d H:i:s", $item->seal_time);
            $item->unseal_time = empty($item->unseal_time) ? "" : date("Y-m-d H:i:s", $item->unseal_time);
        }

        return $result;
    }

    //头像批量审核
    public function batchCheckAvatar($params)
    {
        DB::connection("mysql")->transaction(function () use ($params) {
            $idsStr = $params['ids'];
            $idsArr = explode(",", $idsStr);

            $state = $params['state'];
            $remark = empty($params['remark']) ? "" : $params['remark'];
            sort($idsArr);
            foreach ($idsArr as $id) {
                $avatarInfo = app("model_user_avatar")->where("id", $id)->first();
                if (empty($avatarInfo)) {
                    throw new BasicException(10001, "数据有误！");
                }

                if ($state == 2 || $state == 4) {
                    app("model_user_data")->where("user_id", $avatarInfo->user_id)->update([
                        "head_picture" => $avatarInfo->change_to,
                    ]);
                    RedisService::clearUserInfo($avatarInfo->user_id);
                }
                $avatarInfo->state = $state;
                $avatarInfo->update_time = time();
                $avatarInfo->remark = $remark;
                $avatarInfo->update_admin = app("request")->admin_id;
                $avatarInfo->save();

                $content = $state == 2 ? '头像审核通过' : '头像审核失败' . ($remark ? ':' . $remark : '');
                app("model_user_news")->create([
                    "user_id"     => $avatarInfo->user_id,
                    "messages_id" => 0,
                    "title"       => $content,
                    "add_time"    => time(),
                    "content"     => $content,
                ]);

                Redis::del('user:news:count:' . $avatarInfo->user_id);
                if ($state == 4) {
                    Redis::setex('u:avatar:skill:' . $avatarInfo->user_id, 86400, 1);
                } else {
                    Redis::del('u:avatar:skill:' . $avatarInfo->user_id);
                }
            }
        }, 5);

        return true;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getAvatarQueryList(array $params)
    {
        $whereArr = [];

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }


        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userAvatarModel = app('model_user_avatar');
        $userDataModel = app('model_user_data');

        $result = app('model_user_avatar')
            ->from($userAvatarModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);


        foreach ($result as $item) {
            $item->update_time = empty($item->update_time) ? "" : date("Y-m-d H:i:s", $item->update_time);
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
            $item->nickname = HelperService::wxNickNameFormat($item->nickname);
        }

        return $result;
    }

    /**
     * 删除
     */
    public function delFeedBack($idArr = [])
    {
        $res = app('model_feed_back')->whereIn("id", $idArr)->delete();

        if ($res) {
            return $res;
        }
        throw new BasicException(93044);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getFeedBackQueryList(array $params)
    {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $feedBackModel = app('model_feed_back');
        $userDataModel = app('model_user_data');
        $userModel = app('model_user');

        $result = app('model_feed_back')
            ->from($feedBackModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t2.head_picture",
                "t3.mobile",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);


        foreach ($result as $item) {
            $item->create_time = empty($item->create_time) ? "" : date("Y-m-d H:i:s", $item->create_time);
        }

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getReceiveGiftBagQueryList(array $params)
    {
        $whereArr = [];
        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }

        if (!empty($params["gift_bag_id"])) {
            $whereArr[] = ["t1.gift_bag_id", "=", $params["gift_bag_id"]];
        }

        if (!empty($params["invite_user_code"])) {
            $whereArr[] = ["t3.user_code", "=", $params["invite_user_code"]];
        }

        if (!empty($params["invite_nickname"])) {
            $whereArr[] = ["t3.nickname", "like", "%" . $params["invite_nickname"] . "%"];
        }


        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $giftBagReceiveModel = app('model_gift_bag_receive');
        $userDataModel = app('model_user_data');
        $giftBagModel = app('model_gift_bag');

        $result = app('model_gift_bag_receive')
            ->from($giftBagReceiveModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t4.name as gift_bag_name",
                "t3.nickname as invite_nickname",
                "t3.user_code as invite_user_code",
            ])
            ->with("gift_bag_detail")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t3"), "t1.parent_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($giftBagModel->getTable() . " as t4"), "t1.gift_bag_id", "=", "t4.id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);


        foreach ($result as $item) {
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    //身份认证审核
    public function checkUserAuth($id, $params)
    {
        DB::beginTransaction();
        try {
            $app_status = $params['app_status'];
            $reason = empty($params['reason']) ? "" : $params['reason'];
            $detail = app("model_user_auth")->where("id", $id)->first();
            if (!$detail) {
                throw new BasicException(10001, "记录不存在！");
            }
            if ($detail->app_status != 0) {
                throw new BasicException(10001, "已审核过！");
            }

            if ($detail->is_black == 1) {
                throw new BasicException(10001, "身份证号已被拉黑不能操作");
            }

            $detail->app_status = $app_status;
            $detail->reason = $reason;
            $detail->update_time = date('Y-m-d H:i:s');
            $detail->created_by = app("request")->admin_id;
            $detail->save();

            if ($app_status == 1) {
                $reason = '实名认证通过';
            } else {
                $reason = '实名认证不通过:' . $reason;
            }
            app("repo_user_news")->userNewsAdd([
                "user_id"     => $detail->user_id,
                "messages_id" => 0,
                "title"       => "实名认证",
                "add_time"    => time(),
                "content"     => $reason,
            ]);

            $this->addAdminLog($id . ':' . ($app_status == 1 ? '通过' : '不通过(' . $reason . ')'));
            DB::commit();
            if ($app_status == 1) {
                app("model_user_data")->where("user_id", $detail->user_id)->update([
                    'real_name'       => $detail['full_name'],
                    'identity_number' => $detail['id_number'],
                ]);
                CurlService::actionReport([
                    "action_type" => ActionEnum::ACTION_TYPE_VERIFY_PASS,
                    "user_id"     => $detail->user_id,
                    "is_sync"     => 1,
                ]);

                $reportData = [
                    'source_id'       => 0,
                    'user_id'         => $detail->user_id,
                    'real_name'       => $detail['full_name'] ?? '',
                    'identity_number' => $detail['id_number'] ?? '',
                ];
                (new FrontHttpRequest())->reportUserInfo($reportData);

            }
        } catch (\Exception $exception) {
            DB::rollBack();
            throw  new BasicException(10010, $exception->getMessage());
        }

        return true;
    }

    //身份认证审核
    public function cancelUserAuth($id, $params)
    {
        DB::connection("mysql")->transaction(function () use ($id, $params) {
            $detail = app("model_user_auth")->where("id", $id)->first();
            if (!$detail) {
                throw new BasicException(10001, "记录不存在！");
            }
            if ($detail->app_status == 0) {
                throw new BasicException(10001, "只有已审核的可以撤销！");
            }

            if ($detail->is_black == 1) {
                throw new BasicException(10001, "身份证号已被拉黑不能操作");
            }

            $detail->app_status = 0;
            $detail->reason = "";
            $detail->update_time = date('Y-m-d H:i:s');
            $detail->created_by = app("request")->admin_id;
            $detail->save();

            app("model_user_data")->where("user_id", $detail->user_id)->update([
                'real_name'       => '',
                'identity_number' => '',
            ]);
            app("model_user_news")->create([
                "user_id"     => $detail->user_id,
                "messages_id" => 0,
                "title"       => "实名认证",
                "add_time"    => time(),
                "content"     => '实名认证失效',
            ]);

            $reportData = [
                'source_id'       => 0,
                'user_id'         => $detail->user_id,
                'real_name'       => '',
                'identity_number' => '',
            ];
            (new FrontHttpRequest())->reportUserInfo($reportData);

        }, 5);

        return true;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserAuthQueryList(array $params)
    {
        $whereArr = [];
        $type = $params['type'] ?? 0;//1正常实名2支付宝实名
        if ($type){
            $whereArr[] = ['t1.type', '=', $type];
        }

        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }

        if (!empty($params["sex"])) {
            $whereArr[] = ["t2.sex", "=", $params["sex"]];
        }

        if (isset($params["app_status"])) {
            $whereArr[] = ["t1.app_status", "=", $params["app_status"]];
        }
        if (isset($params['id_number'])){
            $whereArr[] = ['t1.id_number', '=', $params['id_number']];
        }
        if (isset($params['real_name'])){
            $whereArr[] = ['t1.full_name', 'like', '%'.$params['real_name'].'%'];
        }

        if (isset($params['start_time'])){
            $params['start_time'] = $params['start_time'].' 00:00:00';
            $whereArr[] = ['t1.created_time', '>=', $params['start_time']];
        }

        if (isset($params['end_time'])){
            $params['end_time'] = $params['end_time'].' 00:00:00';
            $whereArr[] = ['t1.created_time', '<=', $params['end_time']];
        }
        $userModel = app('model_user');

        if (isset($params['mobile'])){
            $userId = $userModel->where('mobile', $params['mobile'])->value('user_id');
            $whereArr[] = ['t1.user_id', '=', $userId];
        }

        $time = time();

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userAuthModel = app('model_user_auth');
        $userDataModel = app('model_user_data');

        $result = app('model_user_auth')
            ->from($userAuthModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
                "t2.identity_number",
                "t2.sex",
                "t2.real_name",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->where($whereArr);
        if (isset($params['status'])) {
            $userIds = [];
            if ($params['status'] == 1) {  //已注销
                $whereArrs[] = ['deleted', '=', 1];
                $userIds = $userModel->where($whereArrs)->pluck('user_id')->toArray();
            } elseif ($params['status'] == 2) {  //封禁中
                $whereArrs[] = ['seal_time', '>=', $time];
                $userIds = $userModel->where($whereArrs)->pluck('user_id')->toArray();
            }
            if (!empty($userIds)){
                $result = $result->whereIn('t1.user_id', $userIds);
            }
        }
        $result = $result->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);

        //三表联查速度太慢
        $userIds = array_column($result->toArray()['data'], 'user_id');
        $users = $userModel->select('mobile', 'deleted', 'seal_time', 'user_id')->whereIn('user_id', $userIds)->get()->toArray();
        $newUsers = [];
        foreach ($users as $k => $v){
            $newUsers[$v['user_id']] = $v;
        }
        //新加不合理需求,用户有/check/id_number路由的权限才展示
        $checkPermission = $this->checkPermission('user-manager/user-auth/check/id_number', $params['role_id']);
        foreach ($result as $item) {
            $item->is_permission = $checkPermission;    //0=没有权限;1=有权限
            $item->mobile = $newUsers[$item->user_id]['mobile'] ?? '';
            $item->deleted = $newUsers[$item->user_id]['deleted'] ?? '';
            $item->seal_time = $newUsers[$item->user_id]['seal_time'] ?? '';
            //用户状态
            if ($item->deleted == 1){
                $item->status = 1;
            } elseif ($item->seal_time >= $time){
                $item->status = 2;
            } else {
                $item->status = 0;
            }
        }

        return $result;
    }

    /**
     * @Desc:检查是否有某个接口的权限
     * @param $url
     * @param $roleId
     * @return int
     * @author: shiquan
     * @Time: 2022/11/2 11:21
     */
    public function checkPermission($url, $roleId)
    {
        //权限验证，role_id=0表示超级管理员，>0为其它管理员
        if ($roleId > 0) {
            $roleRoutes = app('repo_access')->getRoleAccessRoutes($roleId);
            foreach ($roleRoutes as $route) {
                if ($route['uri'] == $url) {
                    return 1;
                }
            }
            return 0;
        }
        return 1;
    }

    /**
     * 新增
     *
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addUserBank($param)
    {
        $addConfig = app('model_user_bank')->create($param);

        if ($addConfig) {
            return $addConfig;
        }
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delUserBank($idArr = [])
    {
        $res = app('model_user_bank')->whereIn("id", $idArr)->update(['is_deleted' => 1]);

        if ($res) {
            return $res;
        }
        throw new BasicException(93044);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getUserBankQueryList(array $params)
    {
        $whereArr = [];
        if (!empty($params["user_code"])) {
            $whereArr[] = ["t2.user_code", "=", $params["user_code"]];
        }

        if (!empty($params["nickname"])) {
            $whereArr[] = ["t2.nickname", "like", "%" . $params["nickname"] . "%"];
        }

        if (!empty($params["cardholder"])) {
            $whereArr[] = ["t1.cardholder", "like", "%" . $params["cardholder"] . "%"];
        }

        if (!empty($params["bank_num"])) {
            $whereArr[] = ["t1.bank_num", "=", $params["bank_num"]];
        }
        $whereArr[] = ['t1.bank_type', '=', 1];//支付宝
        $whereArr[] = ['t1.is_deleted', '=', 0];
        $whereArr[] = ['t1.check_status', '=', 2];
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $userBankModel = app('model_user_bank');
        $userDataModel = app('model_user_data');

        $result = app('model_user_bank')
            ->from($userBankModel->getTable() . " as t1")
            ->select([
                "t1.*",
                "t2.nickname",
                "t2.user_code",
            ])
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);


        foreach ($result as $item) {
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    /**
     * @param $data  [user_code:用户编号,nickname:用户昵称,sort:升序1 降序2 order_by:1 星愿排序 2气泡币排序 3收益排序]
     * @return array
     */
    public function userMoneyData($data)
    {
        $model = app('model_user')
            ->select(['user_id', 'waterdrop_number', 'money', 'earnings'])
            ->with([
                'user_data' => function ($query) {
                    $query->select(['user_id', 'nickname', 'user_code']);
                },
            ]);
        //->where('money', '>', 0);
        if (!empty($data['user_code'])) {
            $model = $model->whereHas('user_data', function ($query) use ($data) {
                $query->where('user_code', $data['user_code']);
            });
        }
        if (!empty($data['nickname'])) {
            $model = $model->whereHas('user_data', function ($query) use ($data) {
                $query->where('nickname', 'like', '%' . $data['nickname'] . '%');
            });
        }
        if (!empty($data['sort']) && !empty($data['order_by'])) { //排序
            $sort = $data['sort'] == 1 ? 'asc' : 'desc';
            if ($data['order_by'] == 1) { //1星愿排序
                $orderBy = 'waterdrop_number';
            } elseif ($data['order_by'] == 2) { //2气泡币排序
                $orderBy = 'money';
            } else {
                $orderBy = 'earnings'; //3收益排序
            }
            $model = $model->orderBy($orderBy, $sort);
        } else {
            $model = $model->orderBy('user_id', 'desc');
        }
        $list = $model->paginate($data['perPage'], '', '', $data['page'])->toArray();


        if (!empty($list['data'])) {
            $userIdArr = array_column($list['data'], 'user_id');
            $listAcc = app('model_account_money_log')
                ->select(DB::raw('MAX(id) as id,user_id,MAX(created_at) mctime'))
                ->whereIn('user_id', $userIdArr)
                ->where('change_money', '<>', '0')
                ->groupBy('user_id')
                ->pluck('mctime', 'user_id')->toArray();
            $temp = [];
            foreach ($list['data'] as $key => $value) {
                $temp[$key]['user_id'] = $value['user_id'] ?? 0;
                $temp[$key]['user_code'] = $value['user_data']['user_code'] ?? 0;
                $temp[$key]['nickname'] = $value['user_data']['nickname'] ?? '';
                $temp[$key]['waterdrop_number'] = $value['waterdrop_number'] ?? 0;
                $temp[$key]['money'] = $value['money'] ?? 0;
                $temp[$key]['earnings'] = $value['earnings'] ?? 0;
                $temp[$key]['money'] = $value['money'] ?? 0;
                $temp[$key]['update_at'] = isset($listAcc[$value['user_id']]) ? $listAcc[$value['user_id']] : '';
            }
        }

        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $temp,
        ];

        return $result;
    }

    //封禁其他相关的身份证号用户
    public function otherAccount($id_number,$userId,$params, $sealTime, $adminName)
    {
        //封禁身份证号相同的用户
        $list = app('model_user_auth')->whereIn('id_number', $id_number)->where('app_status', '<', UserEnum::USER_AUTH_STATUS_REFUSE)->where('is_black', 0)->get();
        //身份证号相同的用户id
        $relation_user_ids = [];
        //封禁实名认证信息
        foreach ($list as $k => $v) {
           /* $v->is_black = 1;
            $v->app_status_origin = $v['app_status'];
            $v->app_status = 3;
            $v->reason = $params['reason'] ?? '';
            $v->save();*/
            $relation_user_ids[] = $v['user_id'];
        }

        if ($params['is_ban_auth']) {
            //封禁用户账号
            $relation_user_ids = array_diff(array_unique($relation_user_ids), [$userId]);
            foreach ($relation_user_ids as $k => $v) {
                app("model_user_seal")->create([
                    "user_id"   => $v,
                    "seal_time" => $sealTime,
                    "remark"    => $params['remark'] ?? '',
                    "add_time"  => time(),
                    'admin_id'  => app('request')->admin_id,
                    'source' => $params['source'],
                    'url' => $params['url'],
                    'is_ban_auth' => $params['is_ban_auth'],
                    'reason' => $params['reason'],
                    'admin_name' => $adminName
                ]);

                app("model_user")->where("user_id", $v)->update([
                    "seal_time" => $sealTime,
                ]);
            }

            foreach ($relation_user_ids as $k => $v) {
                //记录缓存
                Redis::Setex('u:seal:' . $v, $sealTime - time(), 1);
            }
        }
    }

    /**
     * 获取省市区信息
     * @return array
     */
    public function getRegionAll()
    {
        $return = [];
        $parent = app("model_region")->where('parent_id', 1)->orderBy('id')->orderBy('region_order')->select('id', 'region_name')->get()->toArray();
        $parent = array_column($parent, null, 'id');
        //        $parent = array_column($parent, 'region_name');
        $_parent = [];
        foreach ($parent as $key => $val) {
            $_parent[$key] = $val['region_name'];
        }
        $ids = array_keys($_parent);

        $child = app("model_region")->whereIn('parent_id', $ids)->orderBy('parent_id')->orderBy('id')->orderBy('region_order')->select('id', 'region_name', 'parent_id')->get()->toArray();
        $r = [];
        foreach ($child as $key => $val) {
            $r[$val['parent_id']][] = [
                'id'          => $val['id'],
                'region_name' => $val['region_name'],
            ];
        }
        foreach ($_parent as $key => $val) {
            $return[] = [
                'id'          => $key,
                'region_name' => $val,
                'children'    => $r[$key],
            ];
        }

        return $return;
    }

    /**
     * 用户行为操作列表
     * @param $userId
     * @return array[]
     */
    public function actionLists($userId)
    {
        $listsEnum = [1,2,6,3,4,5,10,12,8,7,9,11,13];
        $userBannedRecord = app('model_user_action_banned')->getUserAction($userId);
        $userBannedAction = [];
        if (!empty($userBannedRecord)) {
            $userBannedAction = json_decode($userBannedRecord->banned_action, true) ?? [];
        }
        // 初始化
        $lists = [
            [
                'id'        =>  2,
                'name'      =>  '用户头像',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  1,
                'name'      =>  '用户昵称',
                'status'    =>  0,          // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  3,
                'name'      =>  '用户相册',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  4,
                'name'      =>  '视频介绍',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  5,
                'name'      =>  '语音介绍',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  6,
                'name'      =>  '个性签名',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  7,
                'name'      =>  '动态',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  8,
                'name'      =>  '私聊',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  9,
                'name'      =>  '聊天广场',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  10,
                'name'      =>  '房间名称',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  11,
                'name'      =>  '房间封面',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  12,
                'name'      =>  '房间公告',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ],
            [
                'id'        =>  13,
                'name'      =>  '房间玩法',
                'status'    =>  0,      // 状态
                'end_time'  => ''        // 解封时间
            ]
        ];
        foreach ($userBannedAction as $key => $value) {
            if (in_array($key,$listsEnum)) {
                switch ($key) {
                    case 1: // 昵称
                        $lists[1]['status'] = 1;
                        $lists[1]['end_time'] = $value;
                        break;
                    case 2: // 用户头像
                        $lists[0]['status'] = 1;
                        $lists[0]['end_time'] = $value;
                        break;
                    case 3: // 用户相册
                        $lists[2]['status'] = 1;
                        $lists[2]['end_time'] = $value;
                        break;
                    case 4: // 视频介绍
                        $lists[3]['status'] = 1;
                        $lists[3]['end_time'] = $value;
                        break;
                    case 5: // 语音介绍
                        $lists[4]['status'] = 1;
                        $lists[4]['end_time'] = $value;
                        break;
                    case 6: // 个性签名
                        $lists[5]['status'] = 1;
                        $lists[5]['end_time'] = $value;
                        break;
                    case 7: // 动态
                        $lists[6]['status'] = 1;
                        $lists[6]['end_time'] = $value;
                        break;
                    case 8: // 私聊
                        $lists[7]['status'] = 1;
                        $lists[7]['end_time'] = $value;
                        break;
                    case 9: // 聊天广场
                        $lists[8]['status'] = 1;
                        $lists[8]['end_time'] = $value;
                        break;
                    case 10: // 房间名称
                        $lists[9]['status'] = 1;
                        $lists[9]['end_time'] = $value;
                        break;
                    case 11: // 房间封面
                        $lists[10]['status'] = 1;
                        $lists[10]['end_time'] = $value;
                        break;
                    case 12: // 房间公告
                        $lists[11]['status'] = 1;
                        $lists[11]['end_time'] = $value;
                        break;
                    case 13: // 房间封面
                        $lists[12]['status'] = 1;
                        $lists[12]['end_time'] = $value;
                        break;
                }
            }
        }
        return $lists;
    }


    /**
     * 封禁时间转换
     * @param $release_time string 转换时间
     * @return string
     */
    protected function switchReleaseTime($release_time)
    {
        switch ($release_time) {
            case 1:
                return time()+3600;
            case 2:
                return time()+3600*8;
            case 3:
                return strtotime('+1 day');
            case 4:
                return strtotime('+3 day');
            case 5:
                return strtotime('+7 day');
            case 6:
                return strtotime('+1 month');
            default:
                return -1;

        }
    }

    /**
     * 用户封禁操作行为
     * @param $params array 数据列表
     * @return mixed
     */
    public function userActionSet($params)
    {
        // 记录用户信息
        if ($params['user_id']) { //封禁用户
            $params['forbid_time_id'] = $params['forbid_time_id'] ?? 0;
            $params['release_time'] = $this->switchReleaseTime($params['forbid_time_id']);
            $userBannedRecord = app('model_user_action_banned')->getUserAction($params['user_id']);
            if ($userBannedRecord) {
                //更新封禁结束时间
                $userBannedAction = json_decode($userBannedRecord->banned_action, true);
                $userBannedAction = $this->setUserBannedAction($params,$userBannedAction);

                if (empty($userBannedAction)) {
                    app('model_user_action_banned')->where('user_id',$params['user_id'])->delete();
                } else {
                    app('model_user_action_banned')->where('id', $userBannedRecord->id)->update([
                        'update_time'   => Carbon::now()->timestamp,
                        'banned_action' => json_encode($userBannedAction),
                        'warning_count' => 0, //清空警告次数
                    ]);
                }
            } else {
                //新增封禁表记录
                $userBannedAction = $this->setUserBannedAction($params);

                $data['banned_action'] = json_encode($userBannedAction);
                app('model_user_action_banned')->insert([
                    'user_id'       => $params['user_id'],
                    'banned_action' => $data['banned_action'],
                    'add_time'      => Carbon::now()->timestamp,
                    'update_time'   => Carbon::now()->timestamp,
                ]);
            }

            app('redis')->del(sprintf(RedisKeyEnum::USER_ACTION, $params['user_id']));
            return true;
        }
    }

    /**
     * 设置用户禁止操作行为信息
     * @param  array  $params   后台操作参数
     * @param  array  $userBannedAction 已封禁参数
     * @return array
     */
    private function setUserBannedAction($params,$userBannedAction = [])
    {
        $service = new ContentService;
        if ($params['type'] == 1) {
            // 封
            $userBannedAction[$params['id']] = $params['release_time'];
            // 内容审核消息同步
            $res = $service->addPunishRecord($params);
            if ($res['code'] != 200) {
                throw new BasicException(0, "内容审核系统同步失败");
            }
        } else {
            // 解
            unset($userBannedAction[$params['id']]);
            // 内容审核消息同步
            $res = $service->addPunishBanReliveRecord($params);
            if ($res['code'] != 200) {
                throw new BasicException(0, "内容审核系统同步失败");
            }
        }

        return $userBannedAction;
    }

    /**
     * @Desc:实名封禁或者解封
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/2 16:16
     */
    public function userAuthBan($params)
    {
        //封禁
        if ($params['type'] == 0){
            return $this->userAuthBanHandle($params);
        } elseif ($params['type'] == 1){
            return $this->userAuthDeblockingHandle($params);
        }
        throw new BasicException(0, "参数错误");
    }

    /**
     * @Desc:实名封禁
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/2 16:16
     */
    public function userAuthBanHandle($params)
    {
        $userAuth = app('model_user_auth')->where('id', $params['id'])->first();
        if (empty($userAuth)){
            throw new BasicException(0, '实名记录不存在');
        }
        if ($userAuth['app_status'] == UserEnum::USER_AUTH_STATUS_BAN){
            throw new BasicException(0, '该实名已被封禁');
        }
        if (isset($params['url']) && empty($params['url'])){
            throw new BasicException(0, '请上传封禁证明');
        }
        //1.2.5家族系统
        if (app('model_family')->where('user_id', $userAuth['user_id'])->value('id')){
            throw new BasicException(100077);
        }

        //实名认证只封一个
        $time = date('Y-m-d H:i:s');
        \DB::beginTransaction();
        try {
            $banData = [
                'user_id'    => $userAuth['user_id'],
                'type'       => $params['type'],
                'reason'     => $params['reason'],
                'admin_id'   => $params['admin_id'],
                'source'     => $params['source'] ?? '',
                'created_at' => $time,
                'updated_at' => $time,
            ];
            if (isset($params['url'])) {
                $banData['url'] = json_encode($params['url']);
            }
            $userAuthData = [
                'app_status'        => UserEnum::USER_AUTH_STATUS_BAN,
                'reason'            => $params['reason'],
                'app_status_origin' => $userAuth['app_status'],
                'is_black'          => 1 //老字段还是需要维护
            ];
            app('model_user_auth')->where('id', $params['id'])->update($userAuthData);

            if (!empty($banData)) {
                app('model_user_auth_ban_log')->insert($banData);
            }
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            throw new BasicException(0, '封禁失败');
        }
        return true;
    }

    /**
     * @Desc:实名解封
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/2 16:16
     */
    public function userAuthDeblockingHandle($params)
    {
        $userAuth = app('model_user_auth')->where('id', $params['id'])->first();
        if (empty($userAuth)){
            throw new BasicException(0, '实名记录不存在');
        }
        if ($userAuth['app_status'] != UserEnum::USER_AUTH_STATUS_BAN){
            throw new BasicException(0, '该实名没有被封禁');
        }

        $time = date('Y-m-d H:i:s');
        \DB::beginTransaction();
        try {
            $banData = [
                'user_id'    => $userAuth['user_id'],
                'type'       => $params['type'],
                'reason'     => $params['reason'],
                'admin_id'   => $params['admin_id'],
                'source'     => $params['source'] ?? '',
                'created_at' => $time,
                'updated_at' => $time,
            ];
            if (isset($params['url']) && !empty($params['url'])) {
                $banData['url'] = json_encode($params['url']);
            }
            $userAuthData = [
                'app_status'        => $userAuth['app_status_origin'],
                'reason'            => $params['reason'],
                'app_status_origin' => $userAuth['app_status'],
                'is_black'          => 0,
            ];
            app('model_user_auth')->where('id', $params['id'])->update($userAuthData);

            if (!empty($banData)) {
                app('model_user_auth_ban_log')->insert($banData);
            }
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            throw new BasicException(0, '解封失败');
        }
        return true;
    }

    /**
     * @Desc:获取用户信息
     * @param $params
     * @return array
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/2 16:35
     */
    public function userInfo($params)
    {
        $userAuth = app('model_user_auth')->where('id', $params['id'])->first();
        if (empty($userAuth)){
            throw new BasicException(0, '实名记录不存在');
        }
        $userId = $userAuth['user_id'];
        $userInfo = RedisService::getUserBaseInfo($userId);
        $userInfo['mobile'] = app('model_user')->where('user_id', $userId)->value('mobile');
        $data = [
            'user_code' => $userInfo['user_code'],
            'nickname' => $userInfo['nickname'],
            'full_name' => $userAuth['full_name'],
            'id_number' => $userAuth['id_number'],
            'mobile' => $userInfo['mobile'],
            'id' => $params['id']
        ];
        return $data;
    }

    /**
     * @Desc:解绑
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/2 18:31
     */
    public function userAuthUntie($params)
    {
        $userAuth = app('model_user_auth')->where('id', $params['id'])->first();
        if (empty($userAuth)){
            throw new BasicException(0, '实名记录不存在');
        }
        if ($userAuth['app_status'] != UserEnum::USER_AUTH_STATUS_PASS){
            throw new BasicException(0, '实名状态有误,无法解绑');
        }
        //1.2.5家族系统
        if (app('model_family')->where('user_id', $userAuth['user_id'])->value('id')){
            throw new BasicException(100076);
        }

        \DB::beginTransaction();
        try {
            $result = app('model_user_auth')->where('id', $params['id'])->update([
                'app_status'        => UserEnum::USER_AUTH_STATUS_UNTIE,
                'app_status_origin' => $userAuth['app_status'],
                'reason'            => $params['reason'],
                'is_black' => 0
            ]);
            $banData = [
                'user_id'  => $userAuth['user_id'],
                'type'     => 2,
                'reason'   => $params['reason'],
                'admin_id' => $params['admin_id'],
            ];
            app('model_user_auth_ban_log')->create($banData);
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            throw new BasicException(0, $exception->getMessage());
        }
        if ($result){
            //解绑需要发一条消息,发消息不应该影响主流程
            app("repo_user_news")->userNewsAdd([
                'user_id'  => $userAuth['user_id'],
                'content'  => '您的实名认证因【'.$params['reason'].'】被解绑，请重新绑定',
                'add_time' => time(),
                'title'    => '实名解绑',
            ]);
            return true;
        } else {
            throw new BasicException(0, '解绑失败');
        }
    }

    /**
     * @Desc:封禁记录
     * @param $params
     * @return mixed
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/3 9:46
     */
    public function banLog($params)
    {
        $pageSize = $params['page_size'] ?? 10;
        $page = $params['page'] ?? 1;
        $userAuth = app('model_user_auth')->where('id', $params['id'])->first();
        if (empty($userAuth)){
            throw new BasicException(0, '实名记录不存在');
        }
        $banLogList = app('model_user_auth_ban_log')->where('user_id', $userAuth['user_id'])->orderBy('id', 'desc')->paginate($pageSize, ['*'], '', $page);
        $adminIds = array_column($banLogList->toArray()['data'],'admin_id');
        $admins = app('model_admin')->select('admin_name', 'admin_id')->whereIn('admin_id', $adminIds)->pluck('admin_name', 'admin_id')->toArray();
        foreach ($banLogList as $item){
            $item->admin_name = $admins[$item->admin_id] ?? '';
        }
        return $banLogList;
    }

    /**
     * @Desc:封禁/解封分类
     * @param $params
     * @return mixed
     * @author: shiquan
     * @Time: 2022/11/3 17:01
     */
    public function banReason($params)
    {
        $type = $params['type'];
        if ($type == 0){
            $list = app('model_user_ban_classify')->where(['type' => 0, 'pid' => 0])->with('classifyMany:pid,title')->get()->toArray();
            $return = [];
            if (!empty($list)){
                foreach ($list as $key => $value){
                    $return[$key]['id'] = $value['id'];
                    $return[$key]['title'] = $value['title'];
                    $return[$key]['second_classify'] = $value['classify_many'];
                }
            }
        } else {
            $return = app('model_user_ban_classify')->where('type', 1)->get()->toArray();
        }
        return $return;
    }
}
